package com.feng.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import com.feng.entity.User;
import com.feng.util.db.DBHelp;
import com.feng.util.db.RowMapper;

public class UserDao {

	DBHelp<User> db = new DBHelp<User>();

	public void create(User user) {
		String sql = "insert into t_user (id,username,`password`,email,active,`enable`) values(?,?,?,?,0,0)";
		db.executeSQL(sql, user.getId(),user.getUserName(),user.getPassword(),user.getEmail());
	}

	

	public User findByEmail(String mail) {
		String sql = "select id,username,`password`,email,ip,lastaccesstime,pic,createtime,active,`enable` from t_user where email=?";
		return db.executeQueryToObject(sql, new UserRowMapper(), mail);
	}
	private class UserRowMapper implements RowMapper<User>{

		public User mapRow(ResultSet rs) throws SQLException {
			User u = new User();
			u.setId(rs.getString("id"));
			u.setUserName(rs.getString("username"));
			u.setPassword(rs.getString("password"));
			u.setEmail(rs.getString("email"));
			u.setIp(rs.getString("ip"));
			u.setLastAccessTime(rs.getString("lastaccesstime"));
			u.setPic(rs.getString("pic"));
			u.setActive(rs.getInt("active"));
			u.setEnable(rs.getBoolean("enable"));
			return u;
		}
		
	}
	public void update(User user) {
		String sql = "update t_user set username=?,password=?,email=?,ip=?,lastaccesstime=?,pic=?,active=?,`enable`=? where id=?";
		db.executeSQL(sql, user.getUserName(),user.getPassword(),user.getEmail(),user.getIp(),user.getLastAccessTime(),user.getPic(),user.getActive(),user.isEnable(),user.getId());
	}



	public User findByNameAndPwd(String name, String pwd) {
		String sql = "select id,username,`password`,email,ip,lastaccesstime,pic,createtime,active,`enable` from t_user where username=? and `password`=?";
		return db.executeQueryToObject(sql, new UserRowMapper(), name,pwd);
	}
}
